const cloud = require('wx-server-sdk');
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database();
const _ = db.command;

/**
 * 根据 matchId 查询“对端”学习记录，并返回对方用户资料
 * 入参: { matchId: string }
 * 返回: { code, message, data?: { peerStudyRecord, partnerInfo } }
 */
exports.main = async (event, context) => {
  const { matchId } = event || {};
  const { OPENID } = cloud.getWXContext();

  if (!OPENID) {
    return { code: 1, message: '用户未登录' };
  }
  if (!matchId) {
    return { code: 400, message: '缺少参数 matchId' };
  }

  try {
    // 查找同一 matchId 下，排除当前用户的“对端学习记录”
    const rs = await db
      .collection('study_records')
      .where({
        matchId,
        userId: _.neq(OPENID)
      })
      .orderBy('createTime', 'desc')
      .limit(1)
      .get();

    if (!rs.data || rs.data.length === 0) {
      return { code: 404, message: '未找到对端学习记录', data: null };
    }

    const peerRecord = rs.data[0];
    const peerUserId =
      peerRecord.userId ||
      peerRecord._openid ||
      peerRecord.openid ||
      peerRecord.openId ||
      '';

    // 读取对端用户资料（默认占位）
    let partnerInfo = {
      nickName: '学习伙伴',
      avatarUrl: '/static/icons/avatar-placeholder.png'
    };

    if (peerUserId) {
      try {
        const ures = await db.collection('users').where({ _openid: peerUserId }).limit(1).get();
        const ui = (ures && ures.data && ures.data[0]) || {};
        partnerInfo = {
          nickName: ui.nickName || ui.nickname || '学习伙伴',
          avatarUrl:
            ui.avatarUrl ||
            ui.avatar_url ||
            ui.avatar ||
            '/static/icons/avatar-placeholder.png'
        };
      } catch (ue) {
        console.log('读取对端用户资料失败，使用默认占位:', ue && (ue.message || ue));
      }
    }

    // 如果头像是 cloud:// fileID，转成临时 https 链接
    try {
      if (
        partnerInfo &&
        typeof partnerInfo.avatarUrl === 'string' &&
        partnerInfo.avatarUrl.indexOf('cloud://') === 0
      ) {
        const tf = await cloud.getTempFileURL({ fileList: [partnerInfo.avatarUrl] });
        const list = (tf && tf.fileList) || [];
        if (list[0] && list[0].tempFileURL) {
          partnerInfo.avatarUrl = list[0].tempFileURL;
        }
      }
    } catch (te) {
      console.log('getTempFileURL 失败，使用原始 avatarUrl:', te && (te.message || te));
    }

    return {
      code: 0,
      message: 'ok',
      data: {
        peerStudyRecord: {
          _id: peerRecord._id,
          userId: peerUserId,
          matchId
        },
        partnerInfo
      }
    };
  } catch (e) {
    console.error('fetchPeerByMatchId 服务器错误:', e);
    return { code: 500, message: '服务器错误', error: e.message || String(e) };
  }
};